const url = require('url');
const bodyParser = require('body-parser');
const superagent = require('superagent');

//code enable webpack-dev-server to support ajax post request
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/*", function(req, res) {
	res.setHeader('Content-Type', 'application/json');
		
	let proxy = null;
	options.proxy.forEach(o => {
		if (req.url.indexOf(o.context) === 0) {
			proxy = o;
		}
	});
	if (!proxy) {
		let pathname = path.join(options.contentBase, req.url);
		fs.createReadStream(pathname).pipe( res );
		return;
	}
	let requestUrl = url.resolve(proxy.target, req.url);
	superagent
		.post(requestUrl)
		.send(req.body)
		.set('Accept', 'application/json')
		.end((err, _res) => {
			res.end(err ? {code : 555} : _res.text);
		});
});